import cv2
import numpy as np


def binarize(p: np.ndarray, limit):
    row = p.shape[0]
    col = p.shape[1]
    for i in range(row):
        for j in range(col):
            if p[i][j] > limit:
                p[i][j] = 255
            else:
                p[i][j] = 0
    return p


def erode(img: np.ndarray, kernel: np.ndarray):
    aft_img = img.copy()
    padding = kernel.shape[0] // 2
    length = img.shape[0]
    for i in range(padding,length-padding):
        for j in range(padding,length-padding):
            if fit(i,j,img,kernel):
                aft_img[i][j]=255
            else:
                aft_img[i][j]=0
    aft_img[0:padding][:] = img[0:padding][:]
    aft_img[length - padding:length][:] = img[length - padding:length][:]
    aft_img[:][0:padding] = img[:][0:padding]
    aft_img[:][length - padding:length] = img[:][length - padding:length]
    return aft_img

def fit(i,j,img:np.ndarray,kernel:np.ndarray):
    width = kernel.shape[0]//2
    for x in range(-width,width):
        for y in range(-width,width):
            if img[i+x][j+y] == 255 and kernel[1+width][1+width]==1:
                continue
            else:
                return False
    return True


if __name__ == '__main__':
    I = cv2.imread('../resource/test.png', 0)
    img = binarize(I, 127)
    # ret, img = cv2.threshold(I, 127, 255, cv2.THRESH_BINARY_INV)
    # m,n =img.shape

    kernel = np.ones((4,4), np.uint8)
    # r = cv2.erode(img, kernel, iterations=1)
    r = erode(img,kernel)
    # 边缘提取
    e = img - r

    cv2.imshow('img', img)
    cv2.imshow('erode', r)
    cv2.imshow('edge', e)
    cv2.imwrite('../resource/output_2.png', e)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
